package service

import (
	"context"
	"errors"
	"github.com/google/uuid"
	"shop_srv/basic/appConfig"
	__ "shop_srv/basic/proto"
	"shop_srv/handler/models"
)

// server is used to implement helloworld.GreeterServer.
type Server struct {
	__.UnimplementedShopServer
}

// SayHello implements helloworld.GreeterServer
func (s *Server) AddGood(_ context.Context, in *__.AddGoodReq) (*__.AddGoodResp, error) {
	var err error
	var g models.Goods

	if in.Title == "" || (in.Price > 10000 && in.Price < 0) || in.Num < 0 {
		return nil, errors.New("参数不合规")
	}

	g.Title = in.Title
	g.TypesId = in.TypesId
	g.Price = in.Price
	g.Num = in.Num
	g.CookieId = in.CookieId
	g.Image = in.Image

	if err = g.CreateGood(appConfig.DB); err != nil {
		return nil, errors.New("橱窗商品添加失败")
	}

	return &__.AddGoodResp{
		Id: int64(g.ID),
	}, nil
}

func (s *Server) AddTypes(_ context.Context, in *__.AddTypesReq) (*__.AddTypesResp, error) {
	var err error
	var t models.Types

	t.Title = in.Title
	t.CookieId = in.CookieId

	if err = t.CreateTypes(appConfig.DB); err != nil {
		return nil, errors.New("分类添加失败")
	}

	return &__.AddTypesResp{
		Id: int64(t.ID),
	}, nil
}

func (s *Server) CreateCookie(_ context.Context, in *__.CreateCookieReq) (*__.CreateCookieResp, error) {
	var err error
	var c models.CooKie

	c.Title = in.Title
	c.TypesId = in.TypesId
	c.UserId = in.UserId
	c.GoodsId = in.GoodsId

	if in.GoodsId == "" {
		return nil, errors.New("橱窗商品关联失败")
	}

	if err = c.CreateCookie(appConfig.DB); err != nil {
		return nil, errors.New("橱窗商品添加失败")
	}

	return &__.CreateCookieResp{
		CookieId: int64(c.ID),
	}, nil
}

func (s *Server) CheckGood(_ context.Context, in *__.CheckGoodReq) (*__.CheckGoodResp, error) {
	var err error
	var g models.Goods
	var msg string
	g.Status = in.Status
	g.Comment = in.Comment

	if err = g.UpdateStatus(appConfig.DB, in.GoodsId); err != nil {
		return nil, errors.New("商品状态同步失败")
	}

	changeMsg(in.Status, msg)

	return &__.CheckGoodResp{
		GoodsId: in.GoodsId,
		Msg:     "审核中",
	}, nil
}

func changeMsg(status int64, msg string) string {
	if status == 1 {
		msg = "待审核"
	} else if status == 2 {
		msg = "审核中"
	} else if status == 3 {
		msg = "驳回"
	} else {
		msg = "审核异常,驳回"
	}

	return msg
}

func (s *Server) AskLog(_ context.Context, in *__.AskLogReq) (*__.AskLogResp, error) {
	var err error
	var a models.AskLog

	a.UserId = in.UserId
	a.GoodsId = in.GoodsId
	a.Content = in.Content

	if err = a.CreateAskLog(appConfig.DB); err != nil {
		return nil, errors.New("商品咨询申请失败")
	}

	return &__.AskLogResp{
		Id: int64(a.ID),
	}, nil
}

func (s *Server) Order(_ context.Context, in *__.OrderReq) (*__.OrderResp, error) {
	var err error
	var o models.Orders

	o.UserId = in.UserId
	o.OrderSn = uuid.NewString()
	o.GoodsId = in.GoodsId

	if err = o.CreateOrder(appConfig.DB); err != nil {
		return nil, errors.New("订单异常")
	}

	return &__.OrderResp{
		OrderSn: o.OrderSn,
	}, nil
}
